﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Text;

namespace QuickFramework.SqlSugarOrm
{
    /// <summary>
    /// 工作单元
    /// </summary>
    public class UnitOfWork : IUnitOfWork
    {
        private ISqlSugarClient m_SqlSugarClient;
        public UnitOfWork()
        {
            m_ID = Guid.NewGuid().ToString();
            
        }
        /// <summary>
        /// 创建工作单元
        /// </summary>
        /// <param name="connectionStringName"></param>
        /// <param name="isMaster"></param>
        /// <returns></returns>
        public IUnitOfWork CreateUoW(string connectionStringName = "Default", bool isMaster = true)
        {
            if (null == m_SqlSugarClient)
            {
                m_SqlSugarClient = DbFactory.CreateSqlSugarClient(connectionStringName, isMaster);
            }
            return this;
        }
        public SqlSugarClient SqlSugarClient
        {
            get
            {
                if (null == m_SqlSugarClient)
                {
                    throw new SqlSugarException("Please Create UnitOfWork!");
                }
                return m_SqlSugarClient as SqlSugarClient;
            }
        }
        private string m_ID;
        /// <summary>
        /// UnitOfWork ID
        /// </summary>
        public string ID
        {
            get { return m_ID; }
        }
        /// <summary>
        /// 开启事务
        /// </summary>
        public IUnitOfWork BeginTransaction()
        {
            SqlSugarClient.BeginTran();
            return this;
        }

        /// <summary>
        /// 提交事务
        /// </summary>
        public void Commit()
        {
            try
            {
                SqlSugarClient.CommitTran();
            }
            catch (Exception ex)
            {
                SqlSugarClient.RollbackTran();
                throw ex;
            }
        }
        /// <summary>
        /// 回滚事务
        /// </summary>
        public void Rollback()
        {
            SqlSugarClient.RollbackTran();
        }
        /// <summary>
        /// 销毁 / 关闭链接对象
        /// </summary>
        public void Dispose()
        {
            SqlSugarClient?.Close();
            SqlSugarClient?.Dispose();
            m_SqlSugarClient = null;
        }
        ~UnitOfWork()
        {
            this.Dispose();
        }
    }
}
